 
package com.pactera.config.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 用户登录成功时返回给前端的数据
 */
@Component
public class ApiAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
         
    	User userDetails = (User) authentication.getPrincipal();
    	
//        String jwtToken = JwtTokenUtil.generateToken(userDetails.getUsername(), 1500);
        String jwtToken = "abc";
      
        
        JSONObject dataJson = new JSONObject();
        dataJson.put("jwtToken", jwtToken);
        
        SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
        if(savedRequest!=null){
          	String targetUrl = savedRequest.getRedirectUrl();
          	logger.info("###### targetUrl: {}", targetUrl);
          	if(targetUrl!=null && !targetUrl.contains("/error")){
          		dataJson.put("targetUrl", targetUrl);
          	}
        }
        
        logger.info("###### Username: {},Login Success!", userDetails.getUsername());
        
        String respJson = JSON.toJSONString(AuthResultVO.result(AuthResultEnum.LOGIN_SUCCESS,dataJson,true));
        
        logger.info("###### Login Resp:{}", respJson);
        
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(respJson);
    }
}
